import os
import json
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QKeySequence, QIcon, QFont
from PyQt5.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit,
    QPushButton, QFileDialog, QListWidget, QListWidgetItem,
    QFormLayout, QWidget, QMessageBox, QGroupBox
)
from qfluentwidgets import (
    PushButton, LineEdit, ComboBox, PrimaryPushButton,
    ToolButton, TransparentToolButton, FluentIcon,
    MessageBox, SwitchButton
)
from config import scan_dir, cache_dir
from utils.messagebox_helper import show_message_box
from config_manager import config  # 导入配置管理器


class HotkeyLineEdit(LineEdit):
    """自定义热键输入控件"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.key_sequence = None
        self.setReadOnly(True)
        self.setPlaceholderText("请按组合键...")

    def keyPressEvent(self, event):
        """捕获按键事件"""
        # 忽略单独的修饰键
        modifiers = event.modifiers()
        key = event.key()

        # 这些修饰键单独按下时不记录
        if key in (Qt.Key_Control, Qt.Key_Shift, Qt.Key_Alt, Qt.Key_Meta):
            return

        # 记录组合键
        self.key_sequence = QKeySequence(modifiers | key)
        self.setText(self.key_sequence.toString())

    def getKeySequence(self):
        """获取设置的按键序列"""
        return self.key_sequence

    def setKeySequence(self, key_sequence):
        """设置按键序列"""
        if isinstance(key_sequence, str):
            self.key_sequence = QKeySequence(key_sequence)
        else:
            self.key_sequence = key_sequence

        if self.key_sequence:
            self.setText(self.key_sequence.toString())


class FolderListWidget(QWidget):
    """文件夹列表控件"""

    def __init__(self, parent=None):
        super().__init__(parent)
        layout = QVBoxLayout(self)

        # 创建列表控件
        self.list_widget = QListWidget()
        self.list_widget.setStyleSheet("""
            QListWidget {
                border: 1px solid #ddd;
                border-radius: 5px;
                padding: 5px;
                background-color: white;
            }
            QListWidget::item {
                border-bottom: 1px solid #eee;
                padding: 5px;
            }
            QListWidget::item:hover {
                background-color: #f0f0f0;
            }
        """)

        # 按钮容器
        btn_layout = QHBoxLayout()
        self.add_btn = PushButton("添加文件夹")
        self.remove_btn = PushButton("移除选中")
        self.add_btn.setIcon(FluentIcon.ADD)
        self.remove_btn.setIcon(FluentIcon.REMOVE)

        btn_layout.addWidget(self.add_btn)
        btn_layout.addWidget(self.remove_btn)

        layout.addWidget(self.list_widget)
        layout.addLayout(btn_layout)

        # 连接信号
        self.add_btn.clicked.connect(self.add_folder)
        self.remove_btn.clicked.connect(self.remove_selected)

    def add_folder(self):
        """添加文件夹"""
        folder = QFileDialog.getExistingDirectory(
            self, "选择要扫描的文件夹", os.path.expanduser("~")
        )

        if folder and folder not in self.get_folders():
            self.list_widget.addItem(folder)

    def remove_selected(self):
        """移除选中的文件夹"""
        selected_items = self.list_widget.selectedItems()
        if not selected_items:
            return

        for item in selected_items:
            row = self.list_widget.row(item)
            self.list_widget.takeItem(row)

    def get_folders(self):
        """获取所有文件夹"""
        folders = []
        for i in range(self.list_widget.count()):
            folders.append(self.list_widget.item(i).text())
        return folders

    def set_folders(self, folders):
        """设置文件夹列表"""
        self.list_widget.clear()
        for folder in folders:
            if os.path.exists(folder):  # 只添加存在的文件夹
                self.list_widget.addItem(folder)


class SettingsDialog(QDialog):
    """设置对话框"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("设置")
        self.setMinimumSize(500, 400)
        self.resize(600, 450)
        self.setup_ui()
        self.load_settings()

    def setup_ui(self):
        """设置UI"""
        main_layout = QVBoxLayout(self)

        # 快捷键设置组
        hotkey_group = QGroupBox("快捷键设置")
        hotkey_layout = QFormLayout()

        self.toggle_hotkey = HotkeyLineEdit()
        hotkey_layout.addRow("显示/隐藏面板:", self.toggle_hotkey)

        hotkey_group.setLayout(hotkey_layout)

        # 文件夹设置组
        folder_group = QGroupBox("扫描文件夹设置")
        folder_layout = QVBoxLayout()

        self.folder_list = FolderListWidget()
        folder_layout.addWidget(self.folder_list)

        folder_group.setLayout(folder_layout)

        # 缓存设置组
        cache_group = QGroupBox("缓存设置")
        cache_layout = QHBoxLayout()

        self.cache_path = LineEdit()
        self.cache_path.setReadOnly(True)

        self.browse_btn = ToolButton(FluentIcon.FOLDER)
        self.browse_btn.setToolTip("浏览...")

        cache_layout.addWidget(QLabel("缓存目录:"))
        cache_layout.addWidget(self.cache_path, 1)
        cache_layout.addWidget(self.browse_btn)

        cache_group.setLayout(cache_layout)

        # 自启动设置组
        autostart_group = QGroupBox("自启动设置")
        autostart_layout = QHBoxLayout()

        autostart_label = QLabel("开机自启动:")
        self.autostart_switch = SwitchButton()

        autostart_layout.addWidget(autostart_label)
        autostart_layout.addWidget(self.autostart_switch)
        autostart_layout.addStretch(1)

        autostart_group.setLayout(autostart_layout)

        # 添加新的显示选项组
        display_group = QGroupBox("显示设置")
        display_layout = QVBoxLayout()

        # 添加"显示非可执行文件"的选项
        non_exe_layout = QHBoxLayout()
        non_exe_label = QLabel("显示非可执行文件的快捷方式:")
        self.show_non_exe_switch = SwitchButton()

        non_exe_layout.addWidget(non_exe_label)
        non_exe_layout.addWidget(self.show_non_exe_switch)
        non_exe_layout.addStretch(1)

        display_layout.addLayout(non_exe_layout)

        # 添加过滤关键词设置
        filter_layout = QVBoxLayout()
        filter_label = QLabel("过滤包含以下关键词的快捷方式(使用逗号分隔):")
        self.filter_keywords_edit = LineEdit()
        self.filter_keywords_edit.setPlaceholderText(
            "例如: 卸载,Uninstall,帮助,Help")

        filter_layout.addWidget(filter_label)
        filter_layout.addWidget(self.filter_keywords_edit)

        display_layout.addLayout(filter_layout)
        display_group.setLayout(display_layout)

        # 按钮区域
        btn_layout = QHBoxLayout()
        self.save_btn = PrimaryPushButton("保存")
        self.cancel_btn = PushButton("取消")
        self.reset_btn = PushButton("恢复默认")

        btn_layout.addWidget(self.reset_btn)
        btn_layout.addStretch()
        btn_layout.addWidget(self.cancel_btn)
        btn_layout.addWidget(self.save_btn)

        # 添加所有组件到主布局
        main_layout.addWidget(hotkey_group)
        main_layout.addWidget(folder_group)
        main_layout.addWidget(cache_group)
        main_layout.addWidget(autostart_group)  # 添加自启动组
        main_layout.addWidget(display_group)    # 添加显示设置组
        main_layout.addStretch()
        main_layout.addLayout(btn_layout)

        self.browse_btn.clicked.connect(self.browse_cache_dir)
        self.save_btn.clicked.connect(self.save_settings)
        self.cancel_btn.clicked.connect(self.reject)
        self.reset_btn.clicked.connect(self.reset_to_default)

    def browse_cache_dir(self):
        """浏览选择缓存目录"""
        directory = QFileDialog.getExistingDirectory(
            self, "选择缓存目录", self.cache_path.text() or os.path.expanduser("~")
        )

        if directory:
            self.cache_path.setText(directory)

    def load_settings(self):
        """加载设置"""
        # 读取配置文件
        config_file = os.path.join(os.path.dirname(
            os.path.abspath(__file__)), "config.json")

        # 默认设置
        default_settings = {
            "hotkey": "Ctrl+Space",
            "scan_dir": scan_dir,
            "cache_dir": cache_dir,
            "show_non_executables": True,  # 默认显示所有文件
            "filter_keywords": ["卸载", "Uninstall"]  # 默认过滤关键词
        }

        try:
            if os.path.exists(config_file):
                with open(config_file, 'r', encoding='utf-8') as f:
                    settings = json.load(f)
            else:
                settings = default_settings
        except Exception as e:
            print(f"加载设置出错: {e}")
            settings = default_settings

        # 应用设置
        self.toggle_hotkey.setKeySequence(settings.get("hotkey", "Ctrl+Space"))
        self.folder_list.set_folders(settings.get("scan_dir", scan_dir))
        self.cache_path.setText(settings.get("cache_dir", cache_dir))

        # 加载显示非可执行文件的设置
        self.show_non_exe_switch.setChecked(
            settings.get("show_non_executables", True)
        )

        # 加载过滤关键词设置
        keywords = settings.get(
            "filter_keywords", default_settings["filter_keywords"])
        self.filter_keywords_edit.setText(", ".join(keywords))

        # 加载自启动设置
        if hasattr(self.parent(), 'isAutoStartEnabled'):
            self.autostart_switch.setChecked(
                self.parent().isAutoStartEnabled())
        else:
            try:
                from app_launcher_fluent import AppLauncherFluent
                app = AppLauncherFluent.__new__(AppLauncherFluent)
                self.autostart_switch.setChecked(app.isAutoStartEnabled())
            except:
                self.autostart_switch.setChecked(False)

    def save_settings(self):
        """保存设置"""
        # 获取当前设置
        hotkey = self.toggle_hotkey.getKeySequence().toString()
        folders = self.folder_list.get_folders()
        cache_dir = self.cache_path.text()
        show_non_executables = self.show_non_exe_switch.isChecked()

        # 处理过滤关键词
        filter_keywords_text = self.filter_keywords_edit.text().strip()
        if filter_keywords_text:
            filter_keywords = [k.strip()
                               for k in filter_keywords_text.split(",") if k.strip()]
        else:
            filter_keywords = []

        # 验证设置
        if not folders:
            show_message_box("错误", "请至少添加一个扫描文件夹", self)
            return

        if not cache_dir:
            show_message_box("错误", "缓存目录不能为空", self)
            return

        # 创建设置对象
        settings = {
            "hotkey": hotkey,
            "scan_dir": folders,
            "cache_dir": cache_dir,
            "show_non_executables": show_non_executables,  # 保存新的设置
            "filter_keywords": filter_keywords  # 保存过滤关键词设置
        }

        # 保存到配置文件
        config_file = os.path.join(os.path.dirname(
            os.path.abspath(__file__)), "config.json")
        try:
            with open(config_file, 'w', encoding='utf-8') as f:
                json.dump(settings, f, ensure_ascii=False, indent=2)

            # 更新配置管理器
            from config_manager import config
            config.update_hotkey(hotkey)
            config.update_scan_directories(folders)
            config.update_cache_directory(cache_dir)
            config.update_show_non_executables(show_non_executables)
            config.update_filter_keywords(filter_keywords)  # 更新过滤关键词

            # 如果存在全局热键处理器，更新热键
            if hasattr(self.parent(), 'hotkey_handler'):
                self.parent().hotkey_handler.update_hotkey(hotkey)

            # 保存自启动设置
            if hasattr(self.parent(), 'toggleAutoStart'):
                self.parent().toggleAutoStart(self.autostart_switch.isChecked())
            else:
                try:
                    from app_launcher_fluent import AppLauncherFluent
                    app = AppLauncherFluent.__new__(AppLauncherFluent)
                    app.toggleAutoStart(self.autostart_switch.isChecked())
                except Exception as e:
                    print(f"保存自启动设置时出错: {e}")

            # 提醒用户设置已保存
            show_message_box(
                "设置已保存",
                "设置已保存，热键已立即生效。\n如果更改了扫描目录或显示设置，请点击刷新按钮重新加载快捷方式。",
                self
            )

            self.accept()
        except Exception as e:
            show_message_box("保存失败", f"保存设置时出错: {e}", self)

    def reset_to_default(self):
        """恢复默认设置"""
        # 使用辅助函数显示确认对话框
        result = show_message_box(
            "确认",
            "确定要恢复默认设置吗？",
            self,
            yes_no=True
        )

        if result:  # 用户选择"是"
            self.toggle_hotkey.setKeySequence("Ctrl+Space")
            self.folder_list.set_folders(["D:\\PortableSoft"])
            self.cache_path.setText("D:\\FuckDesktop")
            self.show_non_exe_switch.setChecked(True)  # 默认显示所有文件类型
            self.filter_keywords_edit.setText("卸载, Uninstall")  # 恢复默认过滤关键词


if __name__ == "__main__":
    # 测试代码
    from PyQt5.QtWidgets import QApplication
    import sys

    app = QApplication(sys.argv)
    dialog = SettingsDialog()
    dialog.exec_()
